<template>
	<div class="" v-if="state !== 'hidden'">
		<el-form
			ref="form"
			:model="form"
			:label-width="'write' == state ? '115px' : 'auto'"
			:class="'write' == state ? 'write-form' : 'read-form'"
			:label-position="'write' == state ? 'top' : 'left'">
			<div class="card-wrap flex-column justify-end card-padding">
				<div class="card-title-wrap">
					<span>基础信息</span>
					<span>采购编号：{{ form.purchaseNo | filterNull }}</span>
					<el-button v-if="'write' == state" @click="addPurchase" type="primary">
						新增车辆采购
					</el-button>
				</div>

				<el-descriptions title="客户信息">
					<el-descriptions-item label="客户名称">
						<span>{{ form.customerName | filterNull }}</span>
					</el-descriptions-item>
					<el-descriptions-item label="业务来源">
						<span>
							<dict-tag
								:options="dict.type.quota_source_business"
								:value="form.businessScopeCode" />
						</span>
					</el-descriptions-item>
					<!--                    <el-descriptions-item label="客户住址">-->
					<!--                        <span>{{ form.customerAddr|filterNull }}</span>-->
					<!--                    </el-descriptions-item>-->
					<el-descriptions-item label="合同时间">
						<span>
							{{ form.timeStart | filterNull }} 至 {{ form.timeFinish | filterNull }}
						</span>
					</el-descriptions-item>
					<el-descriptions-item label="业务担当">
						<span>{{ form.saleName | filterNull }}</span>
					</el-descriptions-item>
					<el-descriptions-item label="申请时间">
						<span>{{ form.applyDate | filterNull }}</span>
					</el-descriptions-item>
					<el-descriptions-item label="车辆类型">
						<span>
							{{ form.carTypeStr | filterNull }}
							<!--                            <dict-tag-->
							<!--                            :options="dict.type.car_classification"-->
							<!--                            :value="form.carClassification"/>-->
						</span>
					</el-descriptions-item>
				</el-descriptions>

				<el-descriptions title="订单信息">
					<el-descriptions-item label="订单编号">
						<span class="table-blue-text" @click="orderDetail">
							{{ form.orderNo | filterNull }}
						</span>
					</el-descriptions-item>
					<el-descriptions-item label="合同编号">
						<span>{{ form.contractNo | filterNull }}</span>
					</el-descriptions-item>
					<el-descriptions-item label="采购类型">
						<span>
							<dict-tag
								:options="dict.type.purchase_type"
								:value="form.purchaseType" />
						</span>
					</el-descriptions-item>
					<!--                    <el-descriptions-item label="采购编号">-->
					<!--                        <span>{{ form.purchaseNo|filterNull }}</span>-->
					<!--                    </el-descriptions-item>-->
					<el-descriptions-item label="出租方">
						<span>{{ form.lessorName | filterNull }}</span>
					</el-descriptions-item>
				</el-descriptions>
			</div>

			<div
				class="card-wrap flex-column justify-end card-padding"
				v-for="(fitem, findex) in form.purchaseInfoList"
				:key="fitem.item_id">
				<div class="card-title-wrap">
					<span>序号{{ findex + 1 }}</span>
					<span></span>

					<div v-if="'write' == state">
						<!--                        <i class="el-icon-circle-plus-outline icon_add" @click="add(findex)"><span>新增</span></i>-->
						<i class="el-icon-remove-outline icon_add" @click="sub(findex)">
							<span>删除</span>
						</i>
						<!--                        <i class="el-icon-document-copy icon_add" @click="copy(findex)"><span>复制</span></i>-->
					</div>
				</div>

				<el-row :gutter="'write' == state ? 130 : 10" style="margin-right: 3%">
					<el-col :span="24">
						<span class="mini-title">车辆采购信息</span>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="品牌车系:"
							prop="seriesId"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择品牌车系',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.seriesId, callback),
									  }
									: {}
							">
							<LinkageSelect2
								v-if="'write' == state"
								disabled
								v-model="fitem.modeldata"
								:key="fitem.modelKey"
								:check-strictly="false"
								style="width: 100%"
								@changeNode="linkageChange($event, fitem)" />

							<span class="text-bold" v-else>
								{{ fitem.brandName || '' }}/{{ fitem.seriesName || '' }}
							</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="车型:"
							prop="modelId"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择车型',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.modelId, callback),
									  }
									: {}
							">
							<ModelSelect
								disabled
								v-if="'write' == state"
								style="width: 100%"
								@sel="modeSel($event, fitem)"
								:modelData="fitem" />
							<span class="text-bold" v-else>{{ fitem.modelName | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="进口车/国产车:"
							prop="domesticImported"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择进口车/国产车',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.domesticImported, callback),
									  }
									: {}
							">
							<el-select
								filterable
								v-if="'write' == state"
								v-model="fitem.domesticImported"
								clearable
								disabled
								style="width: 100%"
								placeholder="">
								<template v-for="dict in dict.type.domestic_imported">
									<el-option
										:label="dict.label"
										:value="dict.value"
										:key="dict.value"></el-option>
								</template>
							</el-select>
							<span v-else>
								<dict-tag
									:options="dict.type.domestic_imported"
									:value="fitem.domesticImported" />
							</span>
						</el-form-item>
					</el-col>

					<!--                    <el-col :span="16">-->
					<!--                        <el-form-item label="品牌车系车型:" prop="modelId"-->
					<!--                                      :rules="'write' == state ? {-->
					<!--                                         required: true,-->
					<!--                                         message: '请选择品牌车系车型',-->
					<!--                                         trigger: 'change',-->
					<!--                                         validator: (rule, value, callback) => validData(rule, fitem.modelId, callback)-->
					<!--                                       }:{}">-->

					<!--                            <linkage-select v-if="'write' == state" disabled-->
					<!--                                            v-model="fitem.modeldata" :key="fitem.modelKey"-->
					<!--                                            :check-strictly="false" style="width: 100%"-->
					<!--                                            @changeNode="linkageChange($event, fitem)"/>-->

					<!--                            <span v-else>{{ fitem.brandName || '' }}/{{-->
					<!--                                    fitem.seriesName || ''-->
					<!--                                }}/{{ fitem.modelName || '' }}</span>-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<!--                    <el-col :span="8">-->
					<!--                        <el-form-item label="品牌名称:" prop="brandId">-->
					<!--                            <linkage-select @changeNode="linkageChange(val, fitem)" />-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<!--                    <el-col :span="8">-->
					<!--                        <el-form-item label="配置:" prop="config"-->
					<!--                                      :rules="'write' == state ? {-->
					<!--                                         required: true,-->
					<!--                                         message: '请输入配置',-->
					<!--                                         trigger: 'blur',-->
					<!--                                         validator: (rule, value, callback) => validData(rule, fitem.config, callback)-->
					<!--                                       }:{}">-->
					<!--                            <el-input v-if="'write' == state" v-model="fitem.config" clearable-->
					<!--                                      placeholder="请输入配置"></el-input>-->
					<!--                            <span v-else>{{fitem.config|filterNull}}</span>-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<el-col :span="8">
						<el-form-item
							label="外观颜色:"
							prop="exteriorColor"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入外观颜色',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.exteriorColor, callback),
									  }
									: {}
							">
							<el-input
								maxlength="50"
								v-if="'write' == state"
								v-model="fitem.exteriorColor"
								clearable
								disabled
								placeholder=""></el-input>

							<span v-else>{{ fitem.exteriorColor | filterNull }}</span>
							<!--                            <el-select v-model="fitem.exteriorColor" filterable placeholder="请选择">-->
							<!--                                <el-option-->
							<!--                                    v-for="item in colorList"-->
							<!--                                    :key="item.value"-->
							<!--                                    :label="item.value"-->
							<!--                                    :value="item.value">-->
							<!--                                </el-option>-->
							<!--                            </el-select>-->
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="内饰颜色:"
							prop="interiorColor"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入内饰颜色',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.interiorColor, callback),
									  }
									: {}
							">
							<el-input
								maxlength="50"
								v-if="'write' == state"
								v-model="fitem.interiorColor"
								clearable
								disabled
								placeholder=""></el-input>
							<span v-else>{{ fitem.interiorColor | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="座位数:"
							prop="seatNum"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入座位数',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.seatNum, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								clearable
								type="text"
								disabled
								@input="value => (fitem.seatNum = value.replace(/[^\d]/g, ''))"
								:maxlength="2"
								v-model="fitem.seatNum"
								placeholder=""></el-input>

							<span v-else>{{ fitem.seatNum | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="租期(月):" prop="leaseTerm">
							<el-input
								maxlength="50"
								disabled
								v-if="'write' == state"
								readonly
								v-model="fitem.leaseTerm"
								clearable
								placeholder=""></el-input>
							<span v-else>{{ fitem.leaseTerm | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="每期租金(元):" prop="monthlyRent">
							<el-input
								maxlength="50"
								disabled
								v-if="'write' == state"
								readonly
								v-model="fitem.monthlyRent"
								clearable
								v-thousand
								placeholder=""></el-input>
							<span v-else v-thousand>{{ fitem.monthlyRent | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="指导价(元):"
							prop="guidancePrice"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入指导价',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.guidancePrice, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								@change="inputChange(findex)"
								disabled
								v-thousand
								@input="
									value => {
										if (isNaN(fitem.guidancePrice)) {
											fitem.guidancePrice = '';
										}
										if (fitem.guidancePrice.indexOf('.') > 0) {
											fitem.guidancePrice = fitem.guidancePrice.slice(
												0,
												fitem.guidancePrice.indexOf('.') + 3,
											);
										}
										fitem.guidancePrice = fitem.guidancePrice.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.guidancePrice"
								placeholder=""></el-input>
							<span v-else v-thousand>{{ fitem.guidancePrice | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="采购单价(元):"
							prop="purchasePrice"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入采购单价',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.purchasePrice, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								v-thousand
								@change="inputChange(findex, 1)"
								@input="
									value => {
										if (isNaN(fitem.purchasePrice)) {
											fitem.purchasePrice = '';
										}
										if (fitem.purchasePrice.indexOf('.') > 0) {
											fitem.purchasePrice = fitem.purchasePrice.slice(
												0,
												fitem.purchasePrice.indexOf('.') + 3,
											);
										}
										fitem.purchasePrice = fitem.purchasePrice.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.purchasePrice"
								placeholder="请输入采购单价"></el-input>
							<span v-else v-thousand>{{ fitem.purchasePrice | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="采购数量:"
							prop="purchaseNum"
							:rules="
								'write' == state
									? {
											required: true,
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(
													rule,
													fitem.purchaseNum,
													callback,
													'purchaseNum',
												),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								@change="inputChange(findex, 2)"
								type="text"
								@input="
									value => {
										fitem.purchaseNum = value.replace(/[^\d]/g, '');
										$forceUpdate();
									}
								"
								v-model="fitem.purchaseNum"
								clearable
								placeholder="请输入采购数量"></el-input>
							<span v-else>{{ fitem.purchaseNum | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="采购总价(元):"
							prop="purchaseTotalPrice"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入采购总价',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.purchaseTotalPrice, callback),
									  }
									: {}
							">
							<el-input
								@change="inputChange(findex, 3)"
								v-if="'write' == state"
								v-thousand
								:ref="`purchaseTotalPrice${fitem.item_id}`"
								@input="
									value => {
										if (isNaN(fitem.purchaseTotalPrice)) {
											fitem.purchaseTotalPrice = '';
										}
										if (fitem.purchaseTotalPrice.indexOf('.') > 0) {
											fitem.purchaseTotalPrice =
												fitem.purchaseTotalPrice.slice(
													0,
													fitem.purchaseTotalPrice.indexOf('.') + 3,
												);
										}
										fitem.purchaseTotalPrice = fitem.purchaseTotalPrice.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model="fitem.purchaseTotalPrice"
								placeholder="请输入采购总价"></el-input>
							<span v-else v-thousand>
								{{ fitem.purchaseTotalPrice | filterNull }}
							</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="折扣率:"
							prop="discountRate"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入指导价和采购单价',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.discountRate, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								readonly
								disabled
								v-model.trim="fitem.discountRate"
								placeholder="请输入指导价和采购单价"></el-input>
							<span v-else>{{ fitem.discountRate | filterNull }}</span>
						</el-form-item>
					</el-col>

					<!--                    <el-col :span="8" style="height: 20px"></el-col>-->

					<el-col :span="8">
						<el-form-item label="车辆产权:" prop="propertyRightId">
							<el-select
								placeholder=""
								filterable
								disabled
								v-if="'write' == state"
								@change="propertyChange"
								v-model="fitem.propertyRightId"
								clearable
								style="width: 100%">
								<template v-for="(item, index) in companyOriginList">
									<el-option
										:label="item.deptName"
										:value="item.deptId"
										:key="index"></el-option>
								</template>
							</el-select>
							<span v-else>{{ fitem.propertyRightName | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="车辆归属:" prop="ascriptionId">
							<el-select
								placeholder=""
								filterable
								disabled
								v-if="'write' == state"
								@change="belongChange"
								v-model="fitem.ascriptionId"
								clearable
								style="width: 100%">
								<template v-for="(item, index) in belongCompanyList">
									<el-option
										:label="item.deptName"
										:value="item.deptId"
										:key="index"></el-option>
								</template>
							</el-select>
							<span v-else>{{ fitem.ascription | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="车辆大区:" prop="cityId">
							<!--                            <RegionCityLink disabled v-if="'write' == state" v-model="fitem.citydata" :key="carKey"-->
							<!--                                            placeholder="" ref="citySelect"-->
							<!--                                            :showAllLevels="false" :defaultSelect="selIds"-->
							<!--                                            @change="citySelectionChange"></RegionCityLink>-->

							<el-input
								v-if="'write' == state"
								v-model="fitem.region"
								disabled
								placeholder=""></el-input>
							<span v-else>{{ fitem.region | filterNull }}</span>
							<!--                            <el-input v-model="form.region" clearable placeholder="请输入车辆大区"></el-input>-->
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="车辆运营:" prop="operationsName">
							<el-input
								maxlength="50"
								v-if="'write' == state"
								v-model="fitem.operationsName"
								clearable
								disabled
								placeholder="请输入车辆运营"></el-input>
							<span v-else>{{ fitem.operationsName | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="车辆性质:"
							prop="carNature"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择车辆性质',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.carNature, callback),
									  }
									: {}
							">
							<el-select
								filterable
								v-if="'write' == state"
								v-model="fitem.carNature"
								clearable
								disabled
								style="width: 100%">
								<template v-for="dict in dict.type.car_nature">
									<el-option
										:label="dict.label"
										:value="dict.value"
										:key="dict.value"></el-option>
								</template>
							</el-select>
							<span v-else>
								<dict-tag
									:options="dict.type.car_nature"
									:value="fitem.carNature" />
							</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="燃油类型:" prop="fuelType">
							<el-select
								placeholder=""
								disabled
								filterable
								v-if="'write' == state"
								v-model="fitem.fuelType"
								clearable
								style="width: 100%">
								<template v-for="dict in dict.type.fuel_type">
									<el-option
										:label="dict.label"
										:value="dict.value"
										:key="dict.value"></el-option>
								</template>
							</el-select>
							<span v-else>
								<dict-tag :options="dict.type.fuel_type" :value="fitem.fuelType" />
							</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="供应商名称:"
							prop="supplierId"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择供应商名称',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.supplierId, callback),
									  }
									: {}
							">
							<el-select
								@change="spCheck($event, fitem)"
								filterable
								v-if="'write' == state"
								v-model="fitem.supplierId"
								clearable
								style="width: 100%">
								<template v-for="dict in supplierList">
									<el-option
										:label="dict.supplierName"
										:value="dict.supplierId"
										:key="dict.supplierId"></el-option>
								</template>
							</el-select>
							<span v-else>{{ fitem.supplierName | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="开户名称:"
							prop="accountId"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择开户名称',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.accountId, callback),
									  }
									: {}
							">
							<!--                            <el-input maxlength="50" v-if="'write' == state"-->
							<!--                                      v-model.trim="fitem.account" placeholder="请输入账户"></el-input>-->
							<el-select
								@change="accountChange($event, fitem)"
								filterable
								v-if="'write' == state"
								v-model="fitem.accountId"
								clearable
								style="width: 100%"
								placeholder="请先选择供应商">
								<template v-for="dict in fitem.accountList">
									<el-option
										:label="dict.accountName"
										:value="dict.accountId"
										:key="dict.accountId"></el-option>
								</template>
							</el-select>
							<span v-else>{{ fitem.account | filterNull }}</span>
						</el-form-item>
					</el-col>

					<!--                    <el-col :span="8">-->
					<!--                        <el-form-item label="排量:" prop="liter">-->
					<!--                            <el-input maxlength="50" v-model="fitem.liter" clearable v-if="'write' == state" disabled-->
					<!--                                      placeholder=""></el-input>-->
					<!--                            <span v-else>{{ fitem.liter|filterNull }}</span>-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<!--                    <el-col :span="8">-->
					<!--                        <el-form-item label="变速类型:" prop="gearType">-->
					<!--                            <el-input maxlength="50" v-model="fitem.gearType" clearable v-if="'write' == state" disabled-->
					<!--                                      placeholder=""></el-input>-->
					<!--                            <span v-else>{{ fitem.gearType|filterNull }}</span>-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<!--                    <el-col :span="8">-->
					<!--                        <el-form-item label="环保标准:" prop="dischargeStandard">-->
					<!--                            <el-input maxlength="50" v-model="fitem.dischargeStandard" clearable v-if="'write' == state"-->
					<!--                                      disabled-->
					<!--                                      placeholder=""></el-input>-->
					<!--                            <span v-else>{{ fitem.dischargeStandard|filterNull }}</span>-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<!--                    <el-col :span="8">-->
					<!--                        <el-form-item label="新车/旧车:" prop="carClassification"-->
					<!--                                      :rules="'write' == state ? {-->
					<!--                                         required: true,-->
					<!--                                         message: '请选择新车/旧车',-->
					<!--                                         trigger: 'change',-->
					<!--                                         validator: (rule, value, callback) => validData(rule, fitem.carClassification, callback)-->
					<!--                                       }:{}">-->
					<!--                            <el-select filterable disabled v-if="'write' == state" v-model="fitem.carClassification"-->
					<!--                                       clearable-->
					<!--                                       style="width: 100%">-->
					<!--                                <template v-for="dict in dict.type.car_classification">-->
					<!--                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>-->
					<!--                                </template>-->
					<!--                            </el-select>-->
					<!--                            <span v-else><dict-tag-->
					<!--                                :options="dict.type.car_classification"-->
					<!--                                :value="fitem.carClassification"/></span>-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<!--                    <el-col :span="8">-->
					<!--                        <el-form-item label="采购类型:" prop="purchaseType"-->
					<!--                                      :rules="'write' == state ? {-->
					<!--                                         required: true,-->
					<!--                                         message: '请选择采购类型',-->
					<!--                                         trigger: 'change',-->
					<!--                                         validator: (rule, value, callback) => validData(rule, fitem.purchaseType, callback)-->
					<!--                                       }:{}">-->
					<!--                            <el-select filterable disabled v-if="'write' == state" v-model="fitem.purchaseType"-->
					<!--                                       clearable-->
					<!--                                       style="width: 100%">-->
					<!--                                <template v-for="dict in dict.type.purchase_type">-->
					<!--                                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>-->
					<!--                                </template>-->
					<!--                            </el-select>-->
					<!--                            <span v-else><dict-tag-->
					<!--                                :options="dict.type.purchase_type"-->
					<!--                                :value="fitem.purchaseType"/></span>-->
					<!--                        </el-form-item>-->
					<!--                    </el-col>-->

					<el-col :span="24">
						<span class="mini-title">车辆支付信息</span>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="定金:"
							prop="deposit"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择定金',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.deposit, callback),
									  }
									: {}
							">
							<el-radio-group v-if="'write' == state" v-model="fitem.deposit">
								<template v-for="dict in dict.type.deposit">
									<el-radio :label="dict.value">{{ dict.label }}</el-radio>
								</template>
							</el-radio-group>
							<span v-else>
								<dict-tag :options="dict.type.deposit" :value="fitem.deposit" />
							</span>
						</el-form-item>
					</el-col>

					<el-col :span="8" v-if="1 == fitem.deposit">
						<el-form-item
							label="定金金额(元/单辆):"
							prop="singleDepositPrice"
							:rules="
								'write' == state
									? {
											required: 1 == fitem.deposit,
											message: '请选择车辆产权',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.singleDepositPrice, callback),
									  }
									: {}
							">
							<el-input
								@change="inputChange(findex, 4)"
								v-thousand
								v-if="'write' == state"
								@input="
									value => {
										if (isNaN(fitem.singleDepositPrice)) {
											fitem.singleDepositPrice = '';
										}
										if (fitem.singleDepositPrice.indexOf('.') > 0) {
											fitem.depositPrice = fitem.singleDepositPrice.slice(
												0,
												fitem.singleDepositPrice.indexOf('.') + 3,
											);
										}
										fitem.singleDepositPrice = fitem.singleDepositPrice.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.singleDepositPrice"
								placeholder="请输入定金金额"></el-input>
							<span v-else v-thousand>
								{{ fitem.singleDepositPrice | filterNull }}
							</span>
						</el-form-item>
					</el-col>

					<el-col :span="8" v-if="1 == fitem.deposit">
						<el-form-item label="余额金额(元/单辆):" prop="singleBalancePrice">
							<el-input
								readonly
								v-if="'write' == state"
								disabled
								v-thousand
								:ref="`singleBalancePrice${fitem.item_id}`"
								v-model.trim="fitem.singleBalancePrice"
								placeholder="自动计算"></el-input>
							<span v-else v-thousand>
								{{ fitem.singleBalancePrice | filterNull }}
							</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="企划计划支付日期:"
							prop="planPayDate"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请选择企划计划支付日期',
											trigger: 'change',
											validator: (rule, value, callback) =>
												validData(rule, fitem.planPayDate, callback),
									  }
									: {}
							">
							<el-date-picker
								v-if="'write' == state"
								v-model="fitem.planPayDate"
								type="datetime"
								placeholder="请选择企划计划支付日期"
								value-format="yyyy-MM-dd HH:mm:ss"
								style="width: 100%"></el-date-picker>
							<span v-else>{{ fitem.planPayDate | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8" v-if="1 == fitem.deposit">
						<el-form-item label="定金金额总计(元):" prop="depositPrice">
							<el-input
								v-thousand
								disabled
								:ref="`depositPrice${fitem.item_id}`"
								v-if="'write' == state"
								@input="
									value => {
										if (isNaN(fitem.depositPrice)) {
											fitem.depositPrice = '';
										}
										if (fitem.depositPrice.indexOf('.') > 0) {
											fitem.depositPrice = fitem.depositPrice.slice(
												0,
												fitem.depositPrice.indexOf('.') + 3,
											);
										}
										fitem.depositPrice = fitem.depositPrice.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.depositPrice"
								placeholder="自动计算"></el-input>
							<span v-else v-thousand>{{ fitem.depositPrice | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8" v-if="1 == fitem.deposit">
						<el-form-item label="余额金额总计(元):" prop="balancePrice">
							<el-input
								readonly
								v-if="'write' == state"
								disabled
								v-thousand
								:ref="`balancePrice${fitem.item_id}`"
								v-model.trim="fitem.balancePrice"
								placeholder="自动计算"></el-input>
							<span v-else v-thousand>{{ fitem.balancePrice | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="16">
						<el-form-item label="备注:" prop="remark">
							<el-input
								maxlength="500"
								v-if="'write' == state"
								type="textarea"
								v-model="fitem.remark"
								clearable
								placeholder="请输入备注"></el-input>
							<span v-else>{{ fitem.remark | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="24" style="margin-top: 15px">
						<span class="mini-title">其他付款信息</span>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="购置税(元/单辆):"
							prop="purchaseTax"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入购置税',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.purchaseTax, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								v-thousand
								@input="
									value => {
										if (isNaN(fitem.purchaseTax)) {
											fitem.purchaseTax = '';
										}
										if (fitem.purchaseTax.indexOf('.') > 0) {
											fitem.purchaseTax = fitem.purchaseTax.slice(
												0,
												fitem.purchaseTax.indexOf('.') + 3,
											);
										}
										fitem.purchaseTax = fitem.purchaseTax.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.purchaseTax"
								placeholder="请输入购置税"></el-input>
							<span v-else v-thousand>{{ fitem.purchaseTax | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="上牌费(元/单辆):"
							prop="registrationFee"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入上牌费',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.registrationFee, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								v-thousand
								@input="
									value => {
										if (isNaN(fitem.registrationFee)) {
											fitem.registrationFee = '';
										}
										if (fitem.registrationFee.indexOf('.') > 0) {
											fitem.registrationFee = fitem.registrationFee.slice(
												0,
												fitem.registrationFee.indexOf('.') + 3,
											);
										}
										fitem.registrationFee = fitem.registrationFee.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.registrationFee"
								placeholder="请输入上牌费"></el-input>
							<span v-else v-thousand>{{ fitem.registrationFee | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="出库费(元/单辆):"
							prop="outboundFee"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入出库费',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.outboundFee, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								v-thousand
								@input="
									value => {
										if (isNaN(fitem.outboundFee)) {
											fitem.outboundFee = '';
										}
										if (fitem.outboundFee.indexOf('.') > 0) {
											fitem.outboundFee = fitem.outboundFee.slice(
												0,
												fitem.outboundFee.indexOf('.') + 3,
											);
										}
										fitem.outboundFee = fitem.outboundFee.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.outboundFee"
								placeholder="请输入出库费"></el-input>
							<span v-else v-thousand>{{ fitem.outboundFee | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="物流费(元/单辆):"
							prop="logisticsFee"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入物流费',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.logisticsFee, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								v-thousand
								@input="
									value => {
										if (isNaN(fitem.logisticsFee)) {
											fitem.logisticsFee = '';
										}
										if (fitem.logisticsFee.indexOf('.') > 0) {
											fitem.logisticsFee = fitem.logisticsFee.slice(
												0,
												fitem.logisticsFee.indexOf('.') + 3,
											);
										}
										fitem.logisticsFee = fitem.logisticsFee.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.logisticsFee"
								placeholder="请输入物流费"></el-input>
							<span v-else v-thousand>{{ fitem.logisticsFee | filterNull }}</span>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item
							label="其他加装费(元/单辆):"
							prop="retrofittingFee"
							:rules="
								'write' == state
									? {
											required: true,
											message: '请输入其他加装费',
											trigger: 'blur',
											validator: (rule, value, callback) =>
												validData(rule, fitem.retrofittingFee, callback),
									  }
									: {}
							">
							<el-input
								v-if="'write' == state"
								v-thousand
								@input="
									value => {
										if (isNaN(fitem.retrofittingFee)) {
											fitem.retrofittingFee = '';
										}
										if (fitem.retrofittingFee.indexOf('.') > 0) {
											fitem.retrofittingFee = fitem.retrofittingFee.slice(
												0,
												fitem.retrofittingFee.indexOf('.') + 3,
											);
										}
										fitem.retrofittingFee = fitem.retrofittingFee.replace(
											new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''),
											'$1',
										);
									}
								"
								v-model.trim="fitem.retrofittingFee"
								placeholder="请输入其他加装费"></el-input>
							<span v-else v-thousand>{{ fitem.retrofittingFee | filterNull }}</span>
						</el-form-item>
					</el-col>
				</el-row>
			</div>

			<div class="card-wrap flex-column justify-end card-padding">
				<!--                <el-form ref="form" :model="form" label-width="80px"-->
				<!--                         label-position="top">-->

				<el-row :gutter="'write' == state ? 130 : 10" style="margin-right: 3%">
					<el-col :span="24">
						<el-form-item label="附件上传:" prop="attachment" style="width: 100%">
							<ImageCommon
								:disabled="'write' != state"
								:up-type="2"
								info="选择附件"
								:limit="999"
								v-model="form.attachment"></ImageCommon>

							<!--                                <FileUpload v-model="form.attachment"></FileUpload>-->
						</el-form-item>
					</el-col>

					<el-col :span="24">
						<el-form-item label="审批附言:" prop="approvalPostscript">
							<el-input
								maxlength="500"
								v-if="'write' == state"
								type="textarea"
								v-model="form.approvalPostscript"
								clearable
								placeholder="请输入审批附言"></el-input>
							<span v-else>{{ form.approvalPostscript | filterNull }}</span>
						</el-form-item>
					</el-col>
				</el-row>

				<!--                </el-form>-->
			</div>
		</el-form>
		<!--        <div class="card-wrap flex justify-end card-padding">-->
		<!--            <el-button :loading="buttonLoading" type="primary" @click="submitForm(0)">保存</el-button>-->
		<!--            <el-button @click="cancel">取消</el-button>-->
		<!--            <el-button :loading="buttonLoading" type="primary" @click="submitForm(1)">提交</el-button>-->
		<!--        </div>-->

		<el-dialog title="选择组织" :visible.sync="dialogVisible" width="35%">
			<div class="head-container">
				<el-tree
					:data="deptOptions"
					:props="defaultProps"
					:expand-on-click-node="false"
					:filter-node-method="filterNode"
					ref="tree"
					node-key="id"
					default-expand-all
					highlight-current
					@node-click="handleNodeClick" />
			</div>
		</el-dialog>

		<el-dialog title="新增" :visible.sync="purchaseOpen" width="75%">
			<!--            show-summary-->
			<el-table
				border
				ref="myTable"
				:data="dialogDataList"
				@selection-change="handleSelectionChange"
				style="width: 100%; margin-top: 10px">
				<el-table-column
					type="selection"
					width="55"
					align="center"
					:selectable="row => row.purchaseNum < row.originNum" />
				<el-table-column
					prop="purchaseNum"
					align="center"
					label="已采购台数"
					show-overflow-tooltip
					min-width="100">
					<template v-slot="{ row }">
						<span>{{ row.purchaseNum | filterNull }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="originNum"
					align="center"
					label="需采购台数"
					show-overflow-tooltip
					min-width="100">
					<template v-slot="{ row }">
						<span>{{ row.originNum | filterNull }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="date"
					align="center"
					label="品牌/车系/车型"
					show-overflow-tooltip
					min-width="310">
					<template v-slot="{ row }">
						{{ row.brandName }}/{{ row.seriesName }}/{{ row.modelName }}
					</template>
				</el-table-column>
				<el-table-column
					prop="seatNum"
					align="center"
					label="座位数"
					show-overflow-tooltip
					min-width="90">
					<template v-slot="{ row }">
						<span>{{ row.seatNum | filterNull }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="liter" align="center" width="100" label="排量">
					<template v-slot="{ row }">
						<span>{{ row.liter | filterNull }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="fuelType" align="center" width="100" label="燃油类型">
					<template v-slot="{ row }">
						<dict-tag :options="dict.type.fuel_type" :value="row.fuelType" />
					</template>
				</el-table-column>
				<el-table-column prop="gearType" align="center" width="100" label="变速类型">
					<template v-slot="{ row }">
						<span>{{ row.gearType | filterNull }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="dischargeStandard"
					align="center"
					width="100"
					label="环保标准">
					<template v-slot="{ row }">
						<span>{{ row.dischargeStandard | filterNull }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="interiorColor" align="center" width="100" label="内饰颜色">
					<template v-slot="{ row }">
						<span>{{ row.interiorColor | filterNull }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="exteriorColor" align="center" width="100" label="外观颜色">
					<template v-slot="{ row }">
						<span>{{ row.exteriorColor | filterNull }}</span>
					</template>
				</el-table-column>
			</el-table>

			<div slot="footer">
				<el-button @click="purchaseOpen = false">取 消</el-button>
				<el-button :loading="buttonLoading" type="primary" @click="dialogConfirm">
					确 定
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { deptTreeSelect, listUser } from '@/api/system/user';
	import {
		purchaseAdd,
		purchaseUpdate,
		purchaseDetail,
		queryParamList,
		supplierAccount,
		recognitionModel,
		toOrderDetail,
	} from '@/api/purchaseManage/purchaseList';
	import { v4 as uuid_v1 } from 'uuid';
	import LinkageSelect from '@/views/components/linkageSelect.vue';
	import { supplierAllList, supplierList } from '@/api/memberManage/vendorList';
	import citySelect from '@/views/components/citySelect.vue';
	import RegionCityLink from '@/views/components/provinceCity/regionCityLink.vue';
	import { listDept } from '@/api/system/dept';
	import LinkageSelect2 from '@/views/components/linkageSelect2.vue';
	import ModelSelect from '@/views/components/modelSelect.vue';

	export default {
		components: { ModelSelect, LinkageSelect2, RegionCityLink, citySelect, LinkageSelect },
		dicts: [
			'car_nature',
			'car_classification',
			'purchase_type',
			'deposit',
			'business_scope',
			'domestic_imported',
			'fuel_type',
			'quota_source_business',
		],
		props: {
			value: {
				default: {},
			},
			state: {
				default: 'write',
			},
		},
		computed: {
			form: {
				get() {
					return this.value;
				},
				set(value) {
					this.$emit('input', value);
				},
			},
			watchPurchaseInfoList() {
				return this.form.purchaseInfoList;
			},
		},
		watch: {
			watchPurchaseInfoList: {
				handler(newVal, oldVal) {
					if (
						this.isFirstChange &&
						this.form.orderPurchaseInfoList != null &&
						this.form.orderPurchaseInfoList.length > 0
					) {
						this.isFirstChange = false;
						// console.log('首次改变', newVal)

						newVal?.forEach(item => {
							item.item_id = uuid_v1();
						});

						this.dialogDataList = _.cloneDeep(this.form.orderPurchaseInfoList);
						// this.dialogDataList = this.mergePurchaseInfo(this.form.orderPurchaseInfoList)
						this.dialogDataList = this.dialogDataList.map(item => {
							// item.originNum = item.purchaseNum
							item.originNum = item.quantityOrderNum;
							return item;
						});
					}

					this.dialogDataList = this.dialogDataList.map(item => {
						let num = 0;
						this.form?.purchaseInfoList?.forEach(pitem => {
							// if(item.modelId === pitem.modelId &&
							//     item.seatNum === pitem.seatNum &&
							//     item.interiorColor === pitem.interiorColor){
							//     num += parseInt(pitem.purchaseNum);
							// }
							if (item.dataId === pitem.dataId) {
								num += parseInt(pitem.purchaseNum);
							}
						});
						item.purchaseNum = num;
						return item;
					});

					// let list = this.mergePurchaseInfo(this.form.purchaseInfoList)
					// this.dialogDataList.forEach(item => {
					//     if (list && list.length > 0) {
					//         let find = list.find(citem => citem.frontCheckCode == item.frontCheckCode);
					//         if (find) {
					//             item.purchaseNum = find.purchaseNum
					//         } else {
					//             item.purchaseNum = 0
					//         }
					//     } else {
					//         item.purchaseNum = 0
					//     }
					// })

					if (
						newVal !== oldVal &&
						this.form.purchaseInfoList &&
						this.form.purchaseInfoList.length > 0
					) {
						for (const forElement of this.form.purchaseInfoList) {
							// this.getSeatList(forElement)
							this.getSpList(forElement.supplierId, forElement);

							this.$nextTick(() => {
								// forElement.item_id = uuid_v1()

								forElement.modeldata = [];
								forElement.modelKey = 0;
								if (forElement.modelId && forElement.modelId != null) {
									//下标0为一级菜单value
									forElement.modeldata[0] = String(forElement.brandId);
									//下标1为二级菜单value
									forElement.modeldata[1] = String(forElement.seriesId);
									//下标1为三级菜单value
									// forElement.modeldata[2] = String(forElement.modelId);
									forElement.modelKey++;
									// console.log('-->>', forElement.modeldata)
								}
								this.$forceUpdate();
							});
						}
					}
				},
				deep: true,
				immediate: true,
			},
		},
		data() {
			return {
				isFirstChange: true,
				buttonLoading: false,
				// form: {
				//     followerIds: null,
				//     purchaseInfoList: [{
				//         id: uuid_v1()
				//     }],
				//     orderCarInfoList:[]
				// },
				supplierList: [],
				dialogVisible: false,
				deptOptions: null,
				defaultProps: {
					children: 'children',
					label: 'label',
				},
				deptId: null,
				deptLabel: null,
				userList: [],
				companyOriginList: [],
				belongCompanyList: [],
				selIds: [],
				modelKey: 0,
				carKey: 0,
				purchaseOpen: false,
				dialogDataList: [],
				selRows: [],
			};
		},
		created() {
			// this.getDeptTree()
			// this.getUserList()
			this.getSupplierList();
			this.getCompanyOrigin();
		},
		mounted() {
			// console.log('/clues/clues/{cluesId}==>', this.$route.query)
			// if (this.$route.query && this.$route.query.purchaseOrderId) {
			//     this.getOldData(this.$route.query.purchaseOrderId)
			// }
		},
		methods: {
			orderDetail() {
				if (this.form.orderNo) {
					toOrderDetail(this.form.orderNo).then(res => {
						this.$router.push({
							name: 'OrderDetails',
							query: {
								type: res.data.carType,
								// beFrom: "PurchaseList",
								orderId: res.data.orderId,
								// preOrderId: res.data.preOrderId,
								calcSchemeId: res.data.calcSchemeId,
								// isMenu: this.$route.query.isMenu
							},
						});
					});
				}
			},

			mergePurchaseInfo(list) {
				let purchaseInfoList = [];
				if (list != undefined && list != null && list.length > 0) {
					purchaseInfoList = _.cloneDeep(list);
				}
				const mergedInfo = {};

				// 遍历购买信息列表
				if (
					purchaseInfoList != undefined &&
					purchaseInfoList != null &&
					purchaseInfoList.length > 0
				) {
					purchaseInfoList.forEach(info => {
						// const { modelId, seatNum, interiorColor } = info;
						// const key = `${modelId}_${seatNum}_${interiorColor}`;
						const { dataId } = info;
						const key = dataId;

						const purchaseNum = parseInt(info.purchaseNum);

						// 如果这个键不存在，则创建一个新对象
						if (!mergedInfo[key]) {
							mergedInfo[key] = { ...info };
						} else {
							// 如果这个键已存在，累加purchaseNum
							mergedInfo[key].purchaseNum += purchaseNum;
						}

						// const frontCheckCode = info.frontCheckCode;
						//
						//
						// // 如果该modelId已经存在于合并信息中，则累加purchaseNum，否则初始化为purchaseNum
						// if (mergedInfo[frontCheckCode]) {
						//     mergedInfo[frontCheckCode].purchaseNum += purchaseNum;
						// } else {
						//     mergedInfo[frontCheckCode] = {...info}; // 使用对象的副本，避免修改原始数据
						//     mergedInfo[frontCheckCode].purchaseNum = purchaseNum;
						// }
					});
				}
				// 转换为数组形式
				const mergedList = Object.values(mergedInfo);
				return mergedList;
			},

			dialogConfirm() {
				if (this.selRows && this.selRows.length > 0) {
					this.selRows = this.selRows.map(item => {
						item.purchaseNum = 1;
						item.item_id = uuid_v1();
						item.purchaseInfoId = null;
						item.modelKey = 0;

						if (item.purchaseNum && item.purchasePrice) {
							item.purchaseTotalPrice = Number(
								item.purchaseNum * item.purchasePrice,
							).toFixed(2);
						} else {
							item.purchaseTotalPrice = null;
						}

						if (item.depositPrice && item.purchaseTotalPrice) {
							item.balancePrice = Number(
								item.purchaseTotalPrice - item.depositPrice,
							).toFixed(2);
						} else {
							item.balancePrice = null;
						}

						if (item.guidancePrice && item.purchasePrice) {
							item.discountRate =
								Math.round(
									(Number(item.guidancePrice - item.purchasePrice) /
										Number(item.guidancePrice)) *
										100,
								) + '%';
						} else {
							item.discountRate = null;
						}

						return item;
					});
					this.form.purchaseInfoList = this.form.purchaseInfoList
						? this.form.purchaseInfoList.concat(_.cloneDeep(this.selRows))
						: _.cloneDeep(this.selRows);

					//相同车型的排在一起
					let map = new Map();
					this.form.purchaseInfoList.forEach(item => {
						if (!map.has(item.modelId)) {
							map.set(item.modelId, []);
						}
						map.get(item.modelId).push(item);
					});
					this.form.purchaseInfoList = Array.from(map.values()).flat();

					this.selRows = [];
					this.$refs.myTable.clearSelection();
					this.purchaseOpen = false;
					this.$forceUpdate();
				} else {
					this.$modal.msgError('请选择');
				}
			},
			handleSelectionChange(val) {
				this.selRows = _.cloneDeep(val);
			},
			addPurchase() {
				this.purchaseOpen = true;
			},

			citySelectionChange(val) {
				if (val.length > 0) {
					this.form.region = val[0].pathNodes[0].label;
					this.form.regionId = val[0].pathNodes[0].value;
					this.form.provinceName = val[0].pathNodes[1].label;
					this.form.provinceId = val[0].pathNodes[1].value;
					this.form.cityName = val[0].pathNodes[2].label;
					this.form.cityId = val[0].pathNodes[2].value;
				} else {
					this.form.regionId = null;
					this.form.region = null;
					this.form.provinceName = null;
					this.form.provinceId = null;
					this.form.cityId = null;
					this.form.cityName = null;
				}

				let find = this.belongCompanyList.find(
					item => this.form.ascriptionId == item.deptId,
				);

				if (this.form.cityId && find && this.form.cityId != find.regionId.split('/')[1]) {
					this.form.ascription = null;
					this.form.ascriptionId = null;
				}

				this.belongCompanyList = [];
				this.getBelongCompany();
			},

			//归属
			belongChange(val) {
				let find = this.belongCompanyList.find(item => val == item.deptId);
				if (find) {
					this.form.ascription = find.deptName ?? null;
					// console.log('belongChange', find)

					this.selIds = [
						find.areaId,
						find.regionId && find.regionId.split('/')[0],
						find.regionId && find.regionId.split('/')[1],
					];
				} else {
					this.selIds = [];
				}
			},

			//产权
			propertyChange(val) {
				this.form.propertyRightName =
					this.companyOriginList.find(item => val == item.deptId)?.deptName ?? null;
				// console.log('propertyChange', this.form.propertyRightName)
			},

			getCompanyOrigin() {
				listDept({
					deptType: '2', //组织类型（1部门 2公司）
					regionId: null, //所在城市（省市区id）
				}).then(res => {
					this.companyOriginList = res.data;
					this.belongCompanyList = res.data;
				});
			},

			getBelongCompany() {
				listDept({
					deptType: '2', //组织类型（1部门 2公司）
					regionId: this.form.cityId, //所在城市（省市区id）
				}).then(res => {
					this.belongCompanyList = res.data;
				});
			},
			spCheck(val, fitem) {
				// fitem.accountList = []
				fitem.accountId = null;
				fitem.account = null;
				if (val) {
					// this.getSpList(val, fitem)
				} else {
					fitem.accountList = [];
				}

				let find = this.supplierList.find(item => val == item.supplierId);
				if (find) {
					fitem.supplierName = find.supplierName;
					fitem.accountList = find.supplierBankAccountVoList;
				} else {
					fitem.supplierName = null;
				}
				this.$forceUpdate();
			},
			getSpList(val, fitem) {
				if (val == undefined || val == null || val == '') {
					return;
				}

				supplierAccount(val).then(res => {
					fitem.accountList = res.data;

					this.$forceUpdate();
				});
			},
			accountChange(val, fitem) {
				let find = fitem.accountList.find(item => val == item.accountId);
				if (find) {
					fitem.account = find.accountName;
				} else {
					fitem.account = null;
				}
				this.$forceUpdate();
			},
			getSupplier(code) {
				return (
					this.supplierList.find(item => item.supplierId == code)?.supplierName ?? '--'
				);
			},
			add(index) {
				this.form.purchaseInfoList.splice(index + 1, 0, {
					item_id: uuid_v1(),
				});
			},
			sub(index) {
				this.form.purchaseInfoList.splice(index, 1);
			},
			copy(index) {
				this.$modal.msgSuccess('已复制');
				if (this.form.purchaseInfoList.length - index > 1) {
					this.form.purchaseInfoList[index + 1] = {
						...this.form.purchaseInfoList[index],
						item_id: this.form.purchaseInfoList[index + 1].item_id,
						dataId: this.form.purchaseInfoList[index + 1].dataId,
					};

					this.$forceUpdate();
				}
			},
			inputChange(findex, type) {
				findex = Number(findex);
				// console.log('数量', this.form.purchaseInfoList[findex].purchaseNum, '--单价--', this.form.purchaseInfoList[findex].purchasePrice)

				if (1 === type || 2 === type) {
					if (
						this.form.purchaseInfoList[findex].purchaseNum &&
						this.form.purchaseInfoList[findex].purchasePrice
					) {
						this.$set(
							this.form.purchaseInfoList[findex],
							'purchaseTotalPrice',
							Number(
								this.form.purchaseInfoList[findex].purchaseNum *
									this.form.purchaseInfoList[findex].purchasePrice,
							).toFixed(2),
						);
						// this.form.purchaseInfoList[findex].purchaseTotalPrice = Number(this.form.purchaseInfoList[findex].purchaseNum * this.form.purchaseInfoList[findex].purchasePrice).toFixed(2)
					} else {
						this.$set(this.form.purchaseInfoList[findex], 'purchaseTotalPrice', null);
						// this.form.purchaseInfoList[findex].purchaseTotalPrice = null
					}
				}

				//数量 * 定金单辆 = 定金总计
				if (
					this.form.purchaseInfoList[findex].purchaseNum &&
					this.form.purchaseInfoList[findex].singleDepositPrice
				) {
					this.$set(
						this.form.purchaseInfoList[findex],
						'depositPrice',
						Number(
							this.form.purchaseInfoList[findex].purchaseNum *
								this.form.purchaseInfoList[findex].singleDepositPrice,
						).toFixed(2),
					);
				} else {
					this.$set(this.form.purchaseInfoList[findex], 'depositPrice', null);
				}

				//单价 - 定金单辆 = 余额单辆
				if (
					this.form.purchaseInfoList[findex].purchasePrice &&
					this.form.purchaseInfoList[findex].singleDepositPrice
				) {
					this.$set(
						this.form.purchaseInfoList[findex],
						'singleBalancePrice',
						Number(
							this.form.purchaseInfoList[findex].purchasePrice -
								this.form.purchaseInfoList[findex].singleDepositPrice,
						).toFixed(2),
					);
				} else {
					this.$set(this.form.purchaseInfoList[findex], 'singleBalancePrice', null);
				}

				//数量 * 余额单辆 = 余额总计
				if (
					this.form.purchaseInfoList[findex].purchaseNum &&
					this.form.purchaseInfoList[findex].singleBalancePrice
				) {
					this.$set(
						this.form.purchaseInfoList[findex],
						'balancePrice',
						Number(
							this.form.purchaseInfoList[findex].purchaseNum *
								this.form.purchaseInfoList[findex].singleBalancePrice,
						).toFixed(2),
					);
				} else {
					this.$set(this.form.purchaseInfoList[findex], 'balancePrice', null);
				}

				// if (this.form.purchaseInfoList[findex].depositPrice && this.form.purchaseInfoList[findex].purchaseTotalPrice) {
				//     this.form.purchaseInfoList[findex].balancePrice = Number(this.form.purchaseInfoList[findex].purchaseTotalPrice - this.form.purchaseInfoList[findex].depositPrice).toFixed(2)
				// } else {
				//     this.form.purchaseInfoList[findex].balancePrice = null
				// }

				if (
					this.form.purchaseInfoList[findex].guidancePrice &&
					this.form.purchaseInfoList[findex].purchasePrice
				) {
					this.$set(
						this.form.purchaseInfoList[findex],
						'discountRate',
						Math.round(
							(Number(
								this.form.purchaseInfoList[findex].guidancePrice -
									this.form.purchaseInfoList[findex].purchasePrice,
							) /
								Number(this.form.purchaseInfoList[findex].guidancePrice)) *
								100,
						) + '%',
					);
				} else {
					this.$set(this.form.purchaseInfoList[findex], 'discountRate', null);
				}

				this.$forceUpdate();

				//单价1    数量2    总价3   定金4
				if (1 === type || 2 === type) {
					this.$nextTick(() => {
						let el =
							this.$refs[
								`purchaseTotalPrice${this.form.purchaseInfoList[findex].item_id}`
							];
						el[0].$refs.input.dispatchEvent(new Event('blur'));
					});
				}

				if (2 === type || 4 === type) {
					this.$nextTick(() => {
						let el2 =
							this.$refs[`depositPrice${this.form.purchaseInfoList[findex].item_id}`];
						if (el2 && el2.length > 0) {
							el2[0]?.$refs?.input?.dispatchEvent(new Event('blur'));
						}
					});
				}

				if (1 === type || 4 === type) {
					this.$nextTick(() => {
						let el2 =
							this.$refs[
								`singleBalancePrice${this.form.purchaseInfoList[findex].item_id}`
							];
						if (el2 && el2.length > 0) {
							el2[0]?.$refs?.input?.dispatchEvent(new Event('blur'));
						}
					});
				}

				if (1 === type || 2 === type || 4 === type) {
					this.$nextTick(() => {
						let el2 =
							this.$refs[`balancePrice${this.form.purchaseInfoList[findex].item_id}`];
						if (el2 && el2.length > 0) {
							el2[0]?.$refs?.input?.dispatchEvent(new Event('blur'));
						}
					});
				}
			},
			validData(rule, value, callback, prop) {
				if (prop === 'purchaseNum') {
					if (value <= 0) {
						callback(new Error('采购数量最小为1'));
						return;
					}
				}

				// console.log('aaa', rule, value, callback)
				if (rule.required && !value) {
					// this.$modal.msgError(`未填写${value}`);
					callback(new Error(rule.message));
				} else {
					callback();
				}
			},
			getSupplierList() {
				supplierAllList({
					approvedFlag: true,
					availableStatus: 0,
					businessTypeCode: 1,
				}).then(res => {
					if (res.code == '200') {
						const { data, total } = res;
						this.supplierList = data;
					}
				});
			},

			modeSel(val, fitem) {
				if (val && val.modelId) {
					if (val.seriesId != fitem.seriesId) {
						this.$set(fitem, 'modeldata', []);
						this.$set(fitem.modeldata, 0, String(val.brandId));
						this.$set(fitem.modeldata, 1, String(val.seriesId));
						this.$set(fitem, 'modelKey', fitem.modelKey + 1);
					}

					this.$set(fitem, 'brandId', val.brandId);
					this.$set(fitem, 'seriesId', val.seriesId);
					this.$set(fitem, 'brandName', val.brandName);
					this.$set(fitem, 'seriesName', val.seriesName);

					this.$set(fitem, 'modelId', val.modelId);
					this.$set(fitem, 'modelName', val.modelName);

					// fitem.modeldata[0] = String(fitem.brandId);
					// //下标1为二级菜单value
					// fitem.modeldata[1] = String(fitem.seriesId);
					// //下标1为三级菜单value
					// // fitem.modeldata[2] = fitem.modelId;
					// fitem.modelKey++
				} else {
					fitem.modelId = null;
					fitem.modelName = null;
				}

				this.getSeatList(fitem);
				this.$forceUpdate();
				this.$refs.form.validateField(['seriesId', 'modelId']);
				this.$nextTick(() => {
					this.$refs.form.validateField(['seriesId', 'modelId']);
				});
			},

			async linkageChange(val, fitem) {
				this.$set(fitem, 'modeldata', []);

				if (val && val[1] && val[1].id) {
					this.$set(fitem, 'brandId', val[0].id);
					this.$set(fitem, 'seriesId', val[1].id);
					this.$set(fitem, 'brandName', val[0].name);
					this.$set(fitem, 'seriesName', val[1].name);

					this.$set(fitem.modeldata, 0, String(fitem.brandId));
					this.$set(fitem.modeldata, 1, String(fitem.seriesId));
				} else {
					this.$set(fitem, 'brandId', null);
					this.$set(fitem, 'seriesId', null);
					this.$set(fitem, 'brandName', null);
					this.$set(fitem, 'seriesName', null);
				}
				this.$set(fitem, 'modelId', null);
				this.$set(fitem, 'modelName', null);

				this.$forceUpdate();
				this.$refs.form.validateField(['seriesId', 'modelId']);
				this.$nextTick(() => {
					this.$refs.form.validateField(['seriesId', 'modelId']);
				});
			},

			// async linkageChange(val, fitem) {
			//     console.log('val---fitem', val, fitem)
			//
			//     if (val) {
			//         fitem.brandId = val[0] ? val[0].id : ''
			//         fitem.seriesId = val[1] ? val[1].id : ''
			//         fitem.modelId = val[2] ? val[2].id : ''
			//         fitem.brandName = val[0] ? val[0].name : ''
			//         fitem.seriesName = val[1] ? val[1].name : ''
			//         fitem.modelName = val[2] ? val[2].name : ''
			//     } else {
			//         fitem.brandId = null
			//         fitem.seriesId = null
			//         fitem.modelId = null
			//         fitem.brandName = null
			//         fitem.seriesName = null
			//         fitem.modelName = null
			//     }
			//
			//     // this.getColorList(fitem)
			//     this.getSeatList(fitem)
			//
			//     this.$forceUpdate()
			// },

			getColorList(fitem) {
				queryParamList({ modelId: fitem.modelId, type: 1 }).then(res => {
					this.$set(
						fitem,
						'colorList',
						res.map(item => item.color),
					);
					// fitem.colorList = res.map(item=>item.color)
				});
			},

			getSeatList(fitem) {
				if (fitem.modelId == undefined || fitem.modelId == null || fitem.modelId == '') {
					return;
				}
				let that = this;

				recognitionModel(fitem.modelId).then(res => {
					if (res.code == '200') {
						for (const dataKey in res.data) {
							if (
								res.data[dataKey] != undefined &&
								res.data[dataKey] != null &&
								res.data[dataKey] != ''
							) {
								// fitem[dataKey] = res.data[dataKey]
								that.$set(fitem, dataKey, res.data[dataKey]);
							}
						}
					}

					that.$nextTick(() => {
						that.$forceUpdate();
					});
				});

				// queryParamList({modelId: fitem.modelId, type: 2}).then(res => {
				//     this.$set(fitem, 'seatList', res.map(item => item.seatNumber))
				//     // fitem.seatList = res.map(item => item.seatNumber)
				//
				//
				//     that.$nextTick(() => {
				//         that.$forceUpdate()
				//     })
				// })
			},

			// 筛选节点
			filterNode(value, data) {
				if (!value) return true;
				return data.label.indexOf(value) !== -1;
			},
			/** 查询组织下拉树结构 */
			getDeptTree() {
				deptTreeSelect().then(response => {
					this.deptOptions = response.data;
				});
			},
			// 节点单击事件
			handleNodeClick(data) {
				// console.log('data', data)

				this.deptLabel = data.label;
				this.deptId = data.id;
				this.form.followerIds = null;

				this.dialogVisible = false;

				this.getUserList();
			},
			getUserList() {
				listUser({
					pageNum: 1,
					pageSize: 100000,
					deptId: this.deptId,
				}).then(response => {
					this.userList = response.rows;
					// this.total = response.total;
					// this.loading = false;
				});
			},
			deptClick() {
				this.dialogVisible = true;
				this.$refs.deptselect.blur();
			},
			async valid(type) {
				let that = this;

				// const allNum = this.form.purchaseInfoList.reduce((pre, item) => {
				//     return pre += Number(item.purchaseNum)
				// }, 0)
				//
				// const allordernum = this.form.orderCarInfoList.reduce((pre, item) => {
				//     return pre += Number(item.carNum)
				// }, 0)
				// console.log('-----', this.form)

				let flag = true;

				// console.log('this.dialogDataList', this.dialogDataList)

				for (const dialogDataListElement of this.dialogDataList) {
					flag = dialogDataListElement.purchaseNum == dialogDataListElement.originNum;
					if (!flag) {
						break;
					}
				}

				if (!flag && 1 != type) {
					this.$modal.msgError('已采购台数和需采购台数需一致！');
					return false;
				}

				if (1 === type) {
					return true;
				}

				return new Promise(resolve => {
					if ('write' == this.state) {
						this.$refs['form'].validate(valid => {
							if (!valid) {
								this.$modal.msgError('必填项未填写');
							}
							resolve(valid);
						});
					} else {
						resolve(true);
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	@import '~@/assets/styles/variables.scss';

	.write-form .el-form-item {
		margin-bottom: 13px !important;
		width: 100%;
	}

	::v-deep .el-form--label-top .el-form-item__label {
		padding: 0;
	}

	//.el-form-item {
	//    margin-bottom: 15px;
	//    width: 70%;
	//}

	.icon_add {
		margin-left: 10px;
		cursor: pointer;
	}

	::v-deep .read-form .el-form-item__label-wrap,
	::v-deep .read-form .el-form-item__content {
		margin-left: 0 !important;
	}

	.el-descriptions {
		margin: 0 -15px;
	}

	::v-deep .el-descriptions {
		margin: 5px -15px 0 !important;
	}

	::v-deep .el-descriptions-item__cell {
		padding: 7px 15px !important;
	}

	::v-deep .el-descriptions__header {
		margin: 5px 0 5px 15px !important;
	}

	::v-deep .el-input.is-disabled .el-input__inner {
		color: $black60;
	}
</style>
